package priv.dajie.tzzq.spider.csgo.c5;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import priv.dajie.tzzq.Base;
import priv.dajie.tzzq.common.ApplicationContextUnit;
import priv.dajie.tzzq.service.PlatformCsgoService;
import priv.dajie.tzzq.spider.Base.Spider;
import priv.dajie.tzzq.spider.csgo.SpiderInfoElement;
import priv.dajie.tzzq.spider.csgo.SpiderInfos;
import priv.dajie.tzzq.spider.model.CsgoItemInfo;
import priv.dajie.tzzq.spider.model.PlatformCsgoItem;

import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName C5CsgoSpider
 * @Description
 * @Author dajie
 * @Date 2019/11/8 11:29 下午
 * @Version V1.0
 **/
public class C5CsgoSpider implements Spider, Runnable {

    private Base httpclient = Base.getClientInstance();
    private Pattern steamNamePattern = Pattern.compile("730/(.*)");
    private SpiderInfos infos;
    private PlatformCsgoService c5CsgoService = (PlatformCsgoService) ApplicationContextUnit.getInstance().getBean("c5CsgoService");


    public C5CsgoSpider(SpiderInfos infos) {
        this.infos = infos;
    }

    @Override
    public void run() {
        startSpider();
    }

    protected void getItem(SpiderInfoElement spiderInfoElement){
        int only = 0;
        int page = 1;
        while (true){
            try {
                URIBuilder uriBuilder = new URIBuilder("https://open.c5game.com/v1/store");
                uriBuilder.setParameter("appid", "730");
                uriBuilder.setParameter("only", String.valueOf(only));
                uriBuilder.setParameter(spiderInfoElement.getKey(), spiderInfoElement.getValue());
                uriBuilder.setParameter("page", String.valueOf(page));
                String jsonStr = httpclient.open(new HttpGet(uriBuilder.build()));
                JSONObject json = JSON.parseObject(jsonStr);
                Integer status = json.getInteger("status");
                if (status == 550){
                    if (only == 0) {
                        page = 1;
                        only = 1;
                        continue;
                    }
                    else {
                        break;
                    }
                }
                if (json.getJSONObject("data")==null){
                    System.out.println(1);
                }

                JSONArray items = json.getJSONObject("data").getJSONArray("list");
                for (int i = 0;i<items.size();i++){
                    JSONObject item = items.getJSONObject(i);
                    String id = item.getString("item_id");
//                    String steamName = null;
                    String name = item.getString("name");
                    CsgoItemInfo csgoItemInfo = new CsgoItemInfo();
                    csgoItemInfo.setName(name);
                    csgoItemInfo.setType(spiderInfoElement.getTypeName());
                    csgoItemInfo.setId(id);
                    PlatformCsgoItem platformCsgoItem = new PlatformCsgoItem();
                    platformCsgoItem.setCsgoItemInfo(csgoItemInfo);
                    if ("S".equals(item.getString("product_type"))){
                        platformCsgoItem.setNum(item.getInteger("num"));
                        platformCsgoItem.setPrice(item.getBigDecimal("price"));
                    }
                    else{
                        platformCsgoItem.setBNum(item.getInteger("num"));
                        platformCsgoItem.setBPrice(item.getBigDecimal("price"));
                    }
                    c5CsgoService.autoAddItem(platformCsgoItem);
                    if(!c5CsgoService.updateInfo(csgoItemInfo)){
                        csgoItemInfo.setSteamName(getSteamName(id));
                        c5CsgoService.addInfo(csgoItemInfo);
                    }
//                    System.out.println(platformCsgoItem);
                }
                page++;
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }


        }

    }

    public String getSteamName(String id){
        String html = httpclient.open(new HttpGet("https://www.c5game.com/csgo/item/index.html?item_id=" + id));
        Document document = Jsoup.parse(html);
        String url = document.selectFirst("div.ft-gray.steamUrl").selectFirst("a").attr("href");
        Matcher matcher = steamNamePattern.matcher(url);
        if (matcher.find()){
            return matcher.group(1);
        }
        return null;
    }

    @Override
    public void startSpider() {
        while (!infos.isEmpty()){
            SpiderInfoElement spiderInfoElement = infos.getSpiderInfoElement();
            System.out.println("剩余:"+ infos.getSize()+" | "+spiderInfoElement);
            getItem(spiderInfoElement);

        }
    }


    public static void main(String[] args) {
        C5CsgoSpider c5CsgoSpider = new C5CsgoSpider(C5CsgoInfo.getSpiderInfos());
        System.out.println("开始爬取");
        c5CsgoSpider.startSpider();
    }
}
